package storage

import (
	"fmt"
	"io"
	"log"
	"time"

	"github.com/jlaffaye/ftp"
)

func NewFTP(address, username, password string) *FTP {
	conn, err := ftp.Dial(address, ftp.DialWithTimeout(5*time.Second))
	if err != nil {
		log.Fatalf("创建FTP客户端失败： %v", err)
	}

	err = conn.Login(username, password)
	if err != nil {
		log.Fatalf("登录FTP服务器失败： %v", err)
	}

	return &FTP{client: conn}
}

type FTP struct {
	client *ftp.ServerConn
}

func (f *FTP) Upload(bucketName, objectName string, reader io.Reader) error {
	err := f.client.Stor(objectName, reader)
	if err != nil {
		return fmt.Errorf("上传文件失败： %v", err)
	}
	return nil
}

func (f *FTP) Download(bucketName, objectName string, writer io.Writer) error {
	r, err := f.client.Retr(objectName)
	if err != nil {
		return fmt.Errorf("下载文件失败： %v", err)
	}
	defer r.Close()

	_, err = io.Copy(writer, r)
	if err != nil {
		return fmt.Errorf("写入文件失败： %v", err)
	}
	return nil
}
